package assess

import (
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/assess"
	assessReq "gitcode.com/G-YT/ANN/server/model/assess/request"
	"gitcode.com/G-YT/ANN/server/model/common/request"
	"gitcode.com/G-YT/ANN/server/model/common/response"
	"regexp"
	"strconv"
	"strings"
)

type CustomerService struct{}

// CreateCustomer 创建客户档案
func (customerService *CustomerService) CreateCustomer(customer assess.Customer) (err error) {
	// 检查手机号是否已存在
	var existingCustomer assess.Customer
	if err = global.GVA_DB.Where("phone = ?", customer.Phone).First(&existingCustomer).Error; err == nil {
		return errors.New("该手机号已存在")
	}
	// 创建客户档案
	err = global.GVA_DB.Create(&customer).Error
	return err
}

// GetCustomerList 分页获取客户档案列表
func (customerService *CustomerService) GetCustomerList(info assessReq.CustomerSearch) (list []assess.Customer, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	// 创建db查询
	db := global.GVA_DB.Model(&assess.Customer{}).Where("hmID = ?", info.HmID)
	var customers []assess.Customer

	// 如果有查询条件
	if info.Keyword != "" {
		query := strings.TrimSpace(info.Keyword)

		// 判断是否为数字（手机号）
		if isNumeric(query) {
			// 按手机号查询
			db = db.Where("phone LIKE ?", "%"+query+"%")
		} else {
			// 按姓名查询
			db = db.Where("name LIKE ?", "%"+query+"%")
		}
	}

	// 获取总数
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	// 分页查询
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	// 按创建时间倒序排列
	err = db.Order("created_at DESC").Find(&customers).Error
	return customers, total, err
}

// GetCustomerById 根据ID获取客户档案
func (customerService *CustomerService) GetCustomerById(id uint) (customer assess.Customer, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&customer).Error
	return
}

// UpdateCustomer 更新客户档案
func (customerService *CustomerService) UpdateCustomer(customer assess.Customer) (err error) {
	// 检查客户是否存在
	var existingCustomer assess.Customer
	if err = global.GVA_DB.Where("id = ?", customer.ID).First(&existingCustomer).Error; err != nil {
		return errors.New("客户档案不存在")
	}

	// 如果修改了手机号，检查新手机号是否已被其他客户使用
	if customer.Phone != existingCustomer.Phone {
		var phoneCheck assess.Customer
		if err = global.GVA_DB.Where("phone = ? AND id != ?", customer.Phone, customer.ID).First(&phoneCheck).Error; err == nil {
			return errors.New("该手机号已被其他客户使用")
		}
	}

	err = global.GVA_DB.Save(&customer).Error
	return err
}

// DeleteCustomer 删除客户档案
func (customerService *CustomerService) DeleteCustomer(id uint) (err error) {
	err = global.GVA_DB.Delete(&assess.Customer{}, id).Error
	return err
}

// DeleteCustomerByIds 批量删除客户档案
func (customerService *CustomerService) DeleteCustomerByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]assess.Customer{}, ids).Error
	return err
}

// GetCustomerPublic 获取客户档案公开信息（不需要鉴权）
func (customerService *CustomerService) GetCustomerPublic() (customerPublic interface{}, err error) {
	// 这里可以返回一些公开的客户统计信息等
	var count int64
	err = global.GVA_DB.Model(&assess.Customer{}).Count(&count).Error
	if err != nil {
		return nil, err
	}

	customerPublic = response.PageResult{
		List:     []interface{}{},
		Total:    count,
		Page:     1,
		PageSize: 10,
	}
	return
}

// isNumeric 判断字符串是否为数字
func isNumeric(s string) bool {
	// 使用正则表达式判断是否为纯数字
	matched, _ := regexp.MatchString(`^\d+$`, s)
	if matched {
		return true
	}

	// 也可以尝试转换为数字
	_, err := strconv.Atoi(s)
	return err == nil
}
